<template>
	<view class="page">
		<!-- 视频选择和预览区域 -->
		<view class="preview-card" @tap="chooseVideo" v-if="!videoUrl && !uploading">
			<view class="video-placeholder">
				<image src="/static/icon-video-add.png" class="add-icon" />
				<view class="add-text">点击选择已拍摄的视频</view>
			</view>
		</view>
		
		<!-- 视频预览/上传中区域（选择后显示） -->
		<view class="preview-card" v-else>
			<!-- 视频预览（上传中/上传成功都显示） -->
			<video 
				class="preview" 
				:src="videoUrl" 
				:poster="''" 
				:autoplay="false" 
				:loop="false" 
				:controls="!uploading && !uploadFailed"
				object-fit="cover" 
				:disable-progress-gesture="uploading || uploadFailed"
			/>
			
			<!-- 上传中状态 -->
			<view class="uploading-mask" v-if="uploading">
				<view class="loading-icon">
					<uni-loading type="spinner" size="40rpx" color="#fff" />
				</view>
				<view class="upload-progress">上传中 {{ uploadProgress }}%</view>
			</view>
			
			<!-- 上传失败状态 -->
			<view class="upload-failed-mask" v-if="uploadFailed">
				<view class="failed-text">上传失败</view>
				<button class="retry-btn" @tap="retryUpload">重新上传</button>
			</view>
			
			<!-- 上传成功后显示 -->
			<view class="video-info" v-if="!uploading && !uploadFailed && videoUrl">
				<view class="duration">{{ Math.ceil(duration) }}s</view>
				<view class="change-video" @tap="chooseVideo">更换视频</view>
			</view>
		</view>

		<view class="form">
			<input 
				class="title" 
				v-model="title" 
				maxlength="30" 
				placeholder="填写标题（最多30字）" 
				@focus="scrollToInput"
			/>
			<textarea 
				class="content" 
				v-model="content" 
				maxlength="200" 
				placeholder="说点什么吧…（最多200字）" 
				@focus="scrollToInput"
			/>
			<view class="counter">{{ title.length }}/30 · {{ content.length }}/200</view>
		</view>

		<view class="actions">
			<button 
				class="btn" 
				type="default" 
				@tap="onSubmit" 
				:disabled="!videoOnlineUrl || !title.trim() || submitting || uploading"
			>
				{{ submitting ? '发布中...' : '确认发布' }}
			</button>
		</view>
	</view>
</template>

<script setup>
import { ref } from 'vue'
import { uploadFile } from '@/api/upload.js' // 需确保接口支持进度回调
import { publishVideo } from '@/api/publish.js'

// 表单数据
const title = ref('')
const content = ref('')

// 视频相关状态
const videoUrl = ref('') // 本地临时预览路径
const videoTempFile = ref(null) // 本地临时文件路径（用于上传）
const videoOnlineUrl = ref('') // 服务器返回的线上地址（上传成功后赋值）
const duration = ref(0) // 视频时长

// 上传状态
const uploading = ref(false) // 上传中
const uploadProgress = ref(0) // 上传进度（0-100）
const uploadFailed = ref(false) // 上传失败

// 发布状态
const submitting = ref(false)

/**
 * 选择本地视频（选择后自动触发上传）
 */
async function chooseVideo() {
	console.log("111111111111111111");
	try {
		// 重置上传状态
		uploading.value = false
		uploadProgress.value = 0
		uploadFailed.value = false
		videoOnlineUrl.value = '' // 更换视频后，清空之前的线上地址

		// Promise 化包装 chooseVideo API
		const res = await new Promise((resolve, reject) => {
			uni.chooseVideo({
				sourceType: ['album'], // 仅选择相册视频
				maxDuration: 60, // 最大60秒
				camera: 'back',
				success: resolve,
				fail: reject
			})
		})
		
		console.log("res",res);
		// 校验返回结果
		// if (res.tempFilePath && res.tempFilePaths?.length) {
		// 	videoUrl.value = res.tempFilePath // 本地预览
		// 	duration.value = res.duration // 视频时长
		// 	videoTempFile.value = res.tempFilePaths[0] // 临时文件路径

		// 	// 选择成功后，自动触发上传
		// 	await uploadVideo()
		// }else{
		// 	console.log("没有满足条件",res.tempFilePath)
		// 	console.log("没有满足条件2",res.tempFilePaths?.length)
		// }
		if (res.tempFilePath) {
			videoUrl.value = res.tempFilePath // 本地预览
			duration.value = res.duration // 视频时长
			videoTempFile.value = res.tempFilePath // 临时文件路径
			// 选择成功后，自动触发上传
			await uploadVideo()
		}else{
			console.log("没有满足条件",res.tempFilePath)
			console.log("没有满足条件2",res.tempFilePaths?.length)
		}
	} catch (error) {
		// 忽略用户取消操作
		if (error.errMsg !== 'chooseVideo:fail cancel') {
			uni.showToast({ title: '选择视频失败，请重试', icon: 'none' })
		}
	}
}

/**
 * 视频上传核心函数（含进度回调）
 */
async function uploadVideo() {
	console.log("触发了吗")
	if (!videoTempFile.value) return
	console.log("触发了吗，ok")
	uploading.value = true
	uploadProgress.value = 0
	uploadFailed.value = false

	try {
		// 调用上传接口，传入进度回调
		const uploadRes = await uploadFile({
			filePath: videoTempFile.value,
			fileType: 'video',
			name: 'videoFile', // 与后端接口字段一致
			// 进度回调（需确保 uploadFile 接口支持 onProgress 参数）
			onProgress: (progressEvent) => {
				const progress = Math.round((progressEvent.loaded / progressEvent.total) * 100)
				uploadProgress.value = progress
			}
		})


		// 上传成功，保存线上地址
		videoOnlineUrl.value = uploadRes.data.url
		uploading.value = false
		uni.showToast({ title: '视频上传成功', icon: 'success', duration: 1000 })
	} catch (error) {
		console.error('视频上传失败:', error)
		uploading.value = false
		uploadFailed.value = true
		uni.showToast({
			title: error.message || '视频上传失败',
			icon: 'none',
			duration: 2000
		})
	}
}

/**
 * 上传失败后重试
 */
function retryUpload() {
	uploadVideo()
}

/**
 * 输入框聚焦时滚动到可视区域（避免被键盘遮挡）
 */
function scrollToInput() {
	setTimeout(() => {
		uni.createSelectorQuery().select('.form').boundingClientRect(rect => {
			if (rect) {
				uni.pageScrollTo({
					scrollTop: rect.top - 20,
					duration: 300
				})
			}
		}).exec()
	}, 300)
}

/**
 * 提交发布（直接使用已上传好的线上地址）
 */
async function onSubmit() {
	const titleVal = title.value.trim()

	// 基础校验
	if (!videoOnlineUrl.value) {
		uni.showToast({ title: '视频尚未上传成功，请稍后', icon: 'none' })
		return
	}
	if (!titleVal) {
		uni.showToast({ title: '请填写标题', icon: 'none' })
		return
	}

	submitting.value = true

	try {
		uni.showLoading({ title: '发布中...' })
		// 直接提交线上视频地址和表单数据
		await publishVideo(
			videoOnlineUrl.value,
			titleVal,
			content.value.trim()
		)

		// 发布成功
		uni.hideLoading()
		uni.showToast({ title: '发布成功', icon: 'success' })
		setTimeout(() => {
			uni.reLaunch({ url: '/pages/index/index' })
		}, 1500)
	} catch (error) {
		uni.hideLoading()
		console.error('发布失败:', error)
		uni.showToast({
			title: error.message || '发布失败，请重试',
			icon: 'none',
			duration: 2000
		})
		submitting.value = false
	}
}
</script>

<style lang="scss" scoped>
.page {
	min-height: 100vh;
	background: #0b0b0b;
	color: #fff;
	padding: 20rpx 24rpx 40rpx;
}

.preview-card {
	position: relative;
	border-radius: 16rpx;
	overflow: hidden;
	background: #000;
	margin-bottom: 24rpx;
}

/* 未选择视频时的占位样式 */
.video-placeholder {
	width: 100%;
	height: 420rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	background: #121212;
	border: 1rpx dashed rgba(255, 255, 255, .1);
	cursor: pointer;
	transition: all .3s ease;
}

.video-placeholder:active {
	background: #1a1a1a;
}

.add-icon {
	width: 80rpx;
	height: 80rpx;
	margin-bottom: 16rpx;
	opacity: .7;
}

.add-text {
	font-size: 28rpx;
	color: #888;
}

/* 视频预览样式 */
.preview {
	width: 100%;
	height: 420rpx;
	background: #000;
}

/* 上传中遮罩 */
.uploading-mask {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: rgba(0, 0, 0, .6);
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	z-index: 2;
}

.loading-icon {
	margin-bottom: 20rpx;
}

.upload-progress {
	font-size: 28rpx;
	color: #fff;
}

/* 上传失败遮罩 */
.upload-failed-mask {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: rgba(0, 0, 0, .6);
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	z-index: 2;
}

.failed-text {
	font-size: 28rpx;
	color: #ff4d4f;
	margin-bottom: 20rpx;
}

.retry-btn {
	background: linear-gradient(135deg, #ff2d55, #ff6a00);
	color: #fff;
	border: none;
	border-radius: 30rpx;
	padding: 10rpx 40rpx;
	font-size: 24rpx;
}

/* 视频信息（上传成功后） */
.video-info {
	position: absolute;
	bottom: 12rpx;
	left: 0;
	width: 100%;
	display: flex;
	justify-content: space-between;
	padding: 0 20rpx;
	box-sizing: border-box;
	z-index: 1;
}

.duration {
	background: rgba(0, 0, 0, .5);
	padding: 6rpx 12rpx;
	border-radius: 24rpx;
	font-size: 22rpx;
}

.change-video {
	background: rgba(0, 0, 0, .5);
	padding: 6rpx 20rpx;
	border-radius: 24rpx;
	font-size: 22rpx;
	cursor: pointer;
}

/* 表单样式 */
.form {
	background: #121212;
	border: 1rpx solid rgba(255, 255, 255, .06);
	border-radius: 16rpx;
	padding: 20rpx;
	margin-bottom: 120rpx; /* 给底部按钮留空间 */
	transition: transform .3s ease;
}

.title {
	background: transparent;
	color: #fff;
	font-size: 30rpx;
	height: 80rpx;
	line-height: 80rpx;
	border-bottom: 1rpx solid rgba(255, 255, 255, .06);
}

.content {
	background: transparent;
	color: #ddd;
	margin-top: 12rpx;
	font-size: 28rpx;
	height: 200rpx;
	width: 100%;
	resize: none;
}

/* 输入框聚焦样式 */
.title:focus, .content:focus {
	outline: none;
	border-color: rgba(255, 106, 0, .3);
}

.counter {
	text-align: right;
	font-size: 22rpx;
	color: #888;
	margin-top: 8rpx;
}

/* 底部按钮区域 */
.actions {
	position: fixed;
	left: 0;
	right: 0;
	bottom: env(safe-area-inset-bottom);
	padding: 16rpx 24rpx 24rpx;
	background: linear-gradient(180deg, rgba(11, 11, 11, 0), rgba(11, 11, 11, .85));
}

.btn {
	width: 100%;
	height: 88rpx;
	border-radius: 12rpx;
	background: linear-gradient(135deg, #ff2d55, #ff6a00);
	color: #fff;
	font-weight: 700;
	border: none;
}

.btn:disabled {
	opacity: .5;
}

/* 适配视频控件样式 */
video::v-deep .uni-video-controls {
	background: linear-gradient(0deg, rgba(0,0,0,.8), transparent);
}
</style>